package com.alibaba.citrus.ots.sales.plan.facade.service.salesplan;

import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.citrus.ots.sales.plan.api.salesplan.CheckPasswordRuleService;
import com.alibaba.citrus.ots.sales.plan.repository.CheckPasswordRuleRepository;
import com.alibaba.citrus.ots.sales.plan.sdo.CheckPasswordRuleSDO;
import com.alibaba.cz.base.tool.result.Result;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class CheckPasswordRuleServiceImpl implements CheckPasswordRuleService {

    @Resource
    private CheckPasswordRuleRepository checkPasswordRuleRepository;

    @Override
    @FacadeInvoker
    public Result<CheckPasswordRuleSDO> checkPasswordQuery() {
        try {
            CheckPasswordRuleSDO checkPasswordRuleSDO = checkPasswordRuleRepository.queryCheckPasswordRule();
            if (Objects.isNull(checkPasswordRuleSDO)) {
                return Result.failure("", "没查到规则");
            }
            return Result.success(checkPasswordRuleSDO);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure("", "查询异常");
        }
    }

    @Override
    @FacadeInvoker
    public Result<String> checkPasswordWriter(CheckPasswordRuleSDO checkPasswordRuleSDO) {
        if (Objects.isNull(checkPasswordRuleSDO)) {
            return Result.failure("", "系统维护中");
        }
        Object checkPasswordRule = checkPasswordRuleRepository.createCheckPasswordRule(checkPasswordRuleSDO);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(checkPasswordRule));
        String id = jsonObject.getString("lastInsertId");
        return Result.success(id);
    }

    private Boolean checkContent(String password) {
        int upperCase = 0, digit = 0, lowerCase = 0;
        char[] chars = password.toCharArray();
        for (char content : chars) {
            if (!Character.isUpperCase(content) || !Character.isDigit(content) || !Character.isLowerCase(content)) {
                return false;
            }
            if (Character.isUpperCase(content)) {
                upperCase = 1;
            }
            if (Character.isDigit(content)) {
                digit = 1;
            }
            if (Character.isLowerCase(content)) {
                lowerCase = 1;
            }
        }

        if (chars.length <= 8 || chars.length >= 18) {
            return false;
        }

        if ((upperCase + digit + lowerCase) < 2) {
            return false;
        }
        return true;
    }

}
